import { RenderPoster } from '@/api/draw'
import { Share } from '@/api/user'
import { Close } from '@react-vant/icons'
import { useLongPress } from 'ahooks'

import { useRef, useState } from 'react'
import { Overlay } from 'react-vant'
import { history, useQuery } from 'umi'

export default function usePoster() {
  const channel = sessionStorage.getItem('channel')
  const shareURL = `${window.location.origin}?channel=${channel || ''}`
  const posterRef = useRef<HTMLImageElement>(null)
  const [visible, setVisible] = useState<boolean>(false)

  // #生成海报
  const { data: posterURL } = useQuery({
    queryKey: ['render:poster'],
    queryFn: () => RenderPoster({ url: shareURL }),
  })

  useLongPress(() => {
    Share()
    setTimeout(() => {
      history.replace('/draw')
    }, 2500)
  }, posterRef)

  function handleClosePoster() {
    setVisible(false)
  }

  function renderNode() {
    return (
      <Overlay onClick={() => handleClosePoster()} zIndex={99999} visible={visible} className="flex items-start justify-center pt-[150px]">
        <div className="relative">
          <Close
            className="absolute top-0 right-0 z-20 text-3xl text-white active:scale-95"
            onClick={() => handleClosePoster()}
          />
          { posterURL && <img ref={posterRef} src={posterURL} className="w-[550px] block" alt="" />}
          <p className="mt-2 text-xs text-center text-white animate-pulse">长按图片保存</p>
        </div>
      </Overlay>
    )
  }

  return {
    open() {
      setVisible(true)
    },
    renderNode,
  }
}
